<template>
  <div class="good-list">
    <search-header
      ref="search"
      :single="true"
      :middle="true"
      name-of-store="商品编号/名称"
      category-of-store="商品类别"
      :limit="limit"
      :current-store-id="$route.params.id"
      type="good"
      @getResultByTag="getResultByTag"
      @resetResult="resetResult"
    />

    <el-card>
      <el-row type="flex" justify="end">
        <el-col :span="2">
          <el-button
            size="small"
            type="primary"
            @click="exportData"
          >导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" border style="width: 100%; margin-top: 10px">
        <el-table-column fixed prop="goodNum" label="商品编号" width="80" />
        <el-table-column label="所属店铺" width="120">
          <template slot-scope="{ row }">
            <span>{{ row.storesListId | storeNameForId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodImgs" label="商品图" width="100">
          <template slot-scope="{ row }">
            <!-- <el-image
              :src="row.goodImgs"
              fit="cover"
              class="img"
            /> -->
            <img v-imgerror="defaultImg" :src="row.goodImgs" alt="" class="img">
          </template>
        </el-table-column>
        <el-table-column prop="goodName" label="商品名称" width="120" />
        <el-table-column prop="goodCategoryId" label="商品类型" width="100">
          <template slot-scope="{ row }">
            <span>{{ row.goodCategoryId | goodCategoryName }} -
              {{ row.subGoodCategoryId | subGoodCategoryName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成本价" width="80">
          <template slot-scope="{ row }">
            <span>{{ row.cost + ' 元' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原价" width="80">
          <template slot-scope="{ row }">
            <span>{{ row.originalPrice + ' 元' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="销售价" width="100" sortable>
          <template slot-scope="{ row }">
            <span>{{ row.price + ' 元' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存量" width="100" sortable />
        <el-table-column
          prop="monthQuantity"
          label="月销售"
          width="100"
          sortable
        />
        <el-table-column
          prop="totalQuantity"
          label="总销售"
          width="100"
          sortable
        />
        <el-table-column
          label="月销售额"
          prop="monthSales"
          width="120"
          sortable
        >
          <template slot-scope="{ row }">
            <span>{{ row.monthSales + ' 元' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="总销售额"
          prop="totalSales"
          width="120"
          sortable
        >
          <template slot-scope="{ row }">
            <span>{{ row.totalSales + ' 元' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isActivity" label="参与活动" width="100" />
        <el-table-column prop="hot" label="热销" width="60" />
        <el-table-column prop="recommend" label="推荐" width="60" />
        <el-table-column prop="status" label="状态" width="60" />
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="{ row }">
            <el-button
              type="text"
              size="small"
              :disabled="row.status === '下架'"
              @click="soiloutClick(row)"
            >下架</el-button>
            <el-button
              type="text"
              size="small"
              @click="delBtn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          background
          :current-page.sync="currentPage"
          :page-sizes="[4, 6, 8, 10]"
          :page-size="limit"
          layout="sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getAllGoods,
  getAllGoodList,
  getAllGoodListByTag,
  soiloutGood,
  delGoodById,
  getAllGoodsByStoreId
} from '@/api/goodserin'
import storeEnum from '@/api/constant/storeerin'
import goodEnum from '@/api/constant/goodserin'
import { tidyTotal } from '@/filters'

export default {
  name: 'GoodList',
  components: {},
  props: {},
  data() {
    return {
      tableData: [], // 店铺列表
      currentPage: 1, // 当前也
      page: 1, // 默认是第一页
      limit: 4, // 请求的店铺数
      total: 0,
      resultList: [],
      defaultImg: 'https://gyq-1306675601.cos.ap-nanjing.myqcloud.com/storeImag1.jpeg'
    }
  },
  computed: {
    goodName() {
      return this.$refs.search.oldStoreName // 商品名称
    },
    storeName() {
      return this.$refs.search.oldStoreNameOfGoods // 所属店铺
    },
    goodCategory() {
      return this.$refs.search.oldStoreCategory // 商品一级分类
    },
    goodSubCategory() {
      return this.$refs.search.oldSubStoreCategory // 商品二级分类
    },
    // 枚举对应的值
    storeNameEnum() {
      const value = storeEnum.storesType.find(
        val => val.id === this.tableData.storesListId
      )
      return value.value
    }
  },
  watch: {},
  created() {
    if (this.$route.params.id) {
      // 根据这个id来获取商品
      this.getGoodListForPage()
      this.getAllGoodsByStoreId()
      // 将店铺名称给到输入框
    } else {
      // 获取总条数
      this.getAllGoods()
      this.getAllGoodList()
    }
  },
  mounted() {},
  methods: {
    async getAllGoodsByStoreId() {
      // 获取总条数
      const res = await getAllGoodsByStoreId({
        storesListId: this.$route.params.id
      })

      this.total = res ? res.length : 0
      return res
    },
    async getGoodListForPage() {
      // 获取每一页的数据
      const res1 = await getAllGoodsByStoreId({
        _page: this.page,
        _limit: this.limit,
        storesListId: this.$route.params.id
      })
      // console.log(res1)
      this.tableData = res1 || []
    },

    // 获取总条数
    async getAllGoods() {
      const res = await getAllGoods()
      this.total = res ? res.length : 0
      return res
    },
    // 获取所有商品列表
    async getAllGoodList() {
      const res = await getAllGoodList(this.page, this.limit)
      this.tableData = res || []
    },
    // 根据关键字获取所有商品列表
    async getAllGoodListByTag() {
      let goodCategory = this.goodCategory
      let goodSubCategory = this.goodSubCategory
      if (this.goodCategory === '全部' || !this.goodCategory) {
        goodCategory = undefined
      }
      if (this.goodSubCategory === '全部' || !this.goodSubCategory) {
        goodSubCategory = undefined
      }
      const res1 = await getAllGoodListByTag({
        // _page: this.page,
        // _limit: this.limit,
        goodName_like: this.goodName,
        storeName_like: this.storeName,
        goodCategoryId_like: goodCategory,
        subGoodCategoryId: goodSubCategory
      })
      const res2 = await getAllGoodListByTag({
        // _page: this.page,
        // _limit: this.limit,
        goodNum_like: this.goodName,
        storeName_like: this.storeName,
        goodCategoryId_like: goodCategory,
        subGoodCategoryId: goodSubCategory
      })
      const res = [res2, res1]
      const totaldata = tidyTotal(res)
      this.tableData = totaldata.slice(0, this.limit)
      this.resultList = totaldata
      this.total = totaldata.length
      return totaldata
    },
    // pageSize 改变时会触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.limit = val
      if (this.isSearch()) {
        // 有内容
        this.tableData = this.resultList.slice(
          val * (this.page - 1),
          val * this.page
        )
      } else if (this.$route.params.id) {
        // 根据店铺id获取数据
        this.getGoodListForPage()
      } else {
        this.getAllGoodList()
      }
    },
    handleCurrentChange(val) {
      this.page = val
      // console.log(`当前页: ${val}`)
      if (this.isSearch()) {
        // 有内容
        this.tableData = this.resultList.slice(
          this.limit * (val - 1),
          this.limit * val
        )
      } else if (this.$route.params.id) {
        // 从店铺页面跳转过来的商品列表
        this.getGoodListForPage()
      } else {
        this.getAllGoodList()
      }
    },
    // 子组件传过来根据内容查询到的数据
    getResultByTag(val, total) {
      // 页码要在第一页
      this.currentPage = 1
      // 需要total
      this.tableData = val
      this.total = total.length
      this.resultList = total
    },
    // 需要区分一下头部查询框中有没有内容
    isSearch() {
      return this.$refs.search.isClickSearch
    },
    // 重置数据
    resetResult() {
      this.getAllGoodList()
      this.getAllGoods()
    },
    // 下架商品
    async soiloutClick(row) {
      try {
        await soiloutGood({
          ...row,
          status: '下架'
        })
        this.getDataAgain()
        this.$message.success('商品下架成功')
      } catch (error) {
        this.$message.error('商品下架失败')
      }
    },
    // 删除店铺信息
    async delBtn(id) {
      try {
        await this.$confirm('确定要删除该商品吗？此操作不可逆')
        await delGoodById(id)
        this.getDataAgain()
        this.$message.success('删除商品成功')
      } catch (error) {
        // console.log(2)
      }
    },
    // 重新拉取
    // 依旧按照不同的情况拉取
    getDataAgain() {
      // 检查table中还有最后一条数据，这个时候，需要改变page的值了
      if (this.tableData.length === 1) {
        this.page--
      }
      if (this.isSearch()) {
        // 有内容
        // this.getGoodsNumsByTag() // 条数
        this.getAllGoodListByTag() // 列表
      } else {
        // 没有内容
        this.getAllGoods() // 条数
        this.getAllGoodList() // 列表
      }
    },
    // 导出商品列表
    exportData() {
      const tHeader = {
        goodNum: '商品编号',
        storesListId: '所属店铺',
        goodName: '商品名称',
        goodCategoryId: '商品一级类型',
        subGoodCategoryId: '商品二级分类',
        cost: '成本价',
        originalPrice: '原价',
        price: '销售价',
        quantity: '库存量',
        monthQuantity: '月销量',
        totalQuantity: '总销量',
        monthSales: '月销售额',
        totalSales: '总销售额',
        isActivity: '参与活动',
        hot: '热销',
        recommend: '推荐',
        status: '状态'
      } // 表头 必填
      const header = Object.keys(tHeader).map(item => tHeader[item])

      import('@/vendor/Export2Excel').then(async excel => {
        let data = []
        // 获取所有数据
        if (this.$route.params.id) {
          // 根据这个id来获取商品
          data = await this.getAllGoodsByStoreId()
        } else if (this.isSearch()) {
          // 获取总条数
          // data = await this.getGoodsNumsByTag()
          data = await this.getAllGoodListByTag()
        } else {
          console.log(1)
          data = await this.getAllGoods()
        }
        // 将data的数据整理成[['', '', ''], ['', '', '']...] 这种形式
        data = this.filterDate(tHeader, data)
        // debugger
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    filterDate(tHeader, list) {
      return list.map(item => {
        // console.log(item)
        return Object.keys(tHeader).map(key => {
          if (key === 'storesListId') {
            const value = storeEnum.storesType.find(val => val.id === item[key])
            return value.value
          } else if (key === 'goodCategoryId') {
            const value = goodEnum.goodCategorys.find(
              val => val.id === item[key]
            )
            return value.categoryName
          } else if (key === 'subGoodCategoryId') {
            const value = goodEnum.subGoodCategorys.find(
              val => val.id === item[key]
            )
            return value.subName
          }
          return item[key]
        })
      })
    }
    // 表头
  }
}
</script>

<style scoped lang="scss">
@import '~@/styles/storeerin';
  .img {
    width: 57px;
    height: 57px;
    border-radius: 10px;
  }

</style>
